import axios from "axios";
import {TOKEN_NAME} from "@//assets/constant/constant";
import $qs from 'qs'
import {Message as $message, Notification as $notify} from "element-ui";
import route from "@//router";
import {REMEMBER_COOKIE} from "@/assets/constant/constant"
import VueCookie from 'vue-cookie'
//vuex
import store from '@//assets/store/index.js'
// 全局设置 axios 发送请求带上cookie
axios.defaults.withCredentials = true

let $axios;

function refreshAxios() {
  $axios = axios.create({
    headers: {
      'MY_HOUSE': localStorage.getItem(TOKEN_NAME) === null ? "" : localStorage.getItem(TOKEN_NAME),
      'USER_ID': store.state.user.id
    }
  })
}

refreshAxios();

/**
 * 更新用户信息
 */
export const updateUser = (id, params) => {
  $axios.post("/api/sysUser/update/" + id, params).then(res => {
    if (res.data.code === 200) {
      $message({
        type: 'success',
        message: '更新成功'
      })
    } else {
      $message({
        type: 'warning',
        message: '更新失败'
      })
    }
  })
}

/**
 * 删除用户
 */
export const delUser = (id) => {
  $axios.delete("/api/sysUser/" + id).then(res => {
    if (res.data.code === 200) {
      $message({
        type: 'success',
        message: '删除成功'
      })
    } else {
      $message({
        type: 'warning',
        message: '删除失败'
      })
    }
  })
}

/**
 * 新增用户
 */
export const saveUser = (params) => {
  $axios.post("/api/sysUser/save", params).then(res => {
    if (res.data.code === 200) {
      $message({
        type: 'success',
        message: '保存成功'
      })
    } else {
      $message({
        type: 'warning',
        message: '用户保存失败'
      })
    }
  })
}
/**
 * 修改菜单节点
 */
export const updateMenuNode = (id, params) => {
  $axios.put("/api/sysMenu/" + id, params).then(res => {
    if (res.data.code === 200) {
      $message({
        type: 'success',
        message: '数据更新成功'
      })
    } else {
      $message({
        type: 'warning',
        message: '数据更新失败'
      })
    }
  })
}
/**
 * 移除菜单节点
 */
export const removeMenuNode = (id) => {
  return $axios.delete("/api/sysMenu/" + id).then(res => {
    if (res.data.code === 200) {
      $message({
        type: 'success',
        message: '删除成功'
      })
    } else {
      $message({
        type: 'warning',
        message: '菜单删除失败'
      })
    }
  })
}
/**
 * 新增菜单
 * @param param
 * @returns {*}
 */
export const addMenuNode = (param) => {
  return $axios.post("/api/sysMenu/save", param).then(res => {
    if (res.data.code === 200) {
      $message({
        type: 'success',
        message: '保存成功'
      })
    } else {
      $message({
        type: 'warning',
        message: '保存失败'
      })
    }
  })
}

/**
 * 获取菜单节点树
 */
export const getNodeTree = () => {
  return $axios.get("/api/sysMenu/nodeTree");
}
/**
 * 获取所有图标
 */
export const getAllIcons = () => {
  return $axios.get("/api/icons/allIcons");
}
/**
 * 更新请求
 */
export const update = (url, id, param) => {
  return $axios.put(url + id, param).then(res => {
    if (res.data.code === 200) {
      $message({
        type: 'success',
        message: '更新成功'
      })
    } else {
      $message({
        type: 'warning',
        message: '更新异常'
      })
    }
  });
}

/**
 * 测试请求
 */
export const test = () => {
  return $axios.delete("/api/test/test");
}

/**
 * 根据id删除元素
 */
export const delById = (url, id) => {
  return $axios.delete(url + id).then(res => {
    if (res.data.code === 200) {
      $message({
        type: 'success',
        message: '删除成功'
      })
    } else {
      $message({
        type: 'warning',
        $message: '删除失败'
      })
    }
  })
}
/**
 * 分页获取用户数据
 */
export const getUserByPage = (page) => {
  return $axios.get("/api/sysUser/allUser/page", {params: page})
}

/**
 * 分页获取菜单数据
 */
export const getMenuByPage = (page) => {
  return $axios.get("/api/sysMenu/allMenu/page", {params: page});
}
/**
 * 分页查找角色
 */
export const getRoleByPage = (page) => {
  return $axios.get("/api/role/allRole/page", {params: page});
}

/**
 * 新增角色
 */
export const addRole = (obj) => {
  $axios.post("/api/role/save", obj).then(res => {
    let code = res.data.code;
    if (code === 200) {
      $message({
        type: 'success',
        message: '角色新增成功'
      })
    } else {
      $message({
        type: 'warning',
        message: "角色新增失败"
      })
    }
  })
}
/**
 * 模糊搜索菜单
 */
export const searchMenuByKey = (key) => {
  return $axios.get("/api/sysMenu/searchByKey/" + key);
}
/**
 * 查询所有的用户信息
 */
export const getAllUserDetails = () => {
  return $axios.get("/api/sysUser/allUser");
}
/**
 * 模糊查询角色信息
 */
export const getRoleByKey = (key) => {
  return $axios.get("/api/role/searchByKey/" + key);
}

/**
 * 获取所有角色信息
 */
export const getAllRole = () => {
  return $axios.get("/api/role/allRole");
}

/**
 * 获取当前用户所能查看的所有菜单信息
 */
export const getAllMenu = () => {
  return $axios.get("/api/sysMenu/allMenu");
}

/**
 * 提交动漫截图数据
 */
export const submitAnimePic = (data) => {
  $axios.post("/api/animeImg/save", data, {'Content-Type': 'application/json'}).then(res => {
    let result = res.data;
    if (result.code === 200) {
      $message({
        type: 'success',
        message: '图像已经提交'
      })
    } else {
      $message({
        type: 'error',
        message: result.msg
      })
    }
  })
}

/**
 * 获取动漫截图信息
 */
export const getAnimeImg = (id) => {
  return $axios.get("/api/animeImg/allPic/" + id);
}
/**
 * 请求动漫信息
 */
export const getAnimes = () => {
  return $axios.get("/api/anime/getMyAnimes");
}
/**
 * 请求游戏
 */
export const getGames = () => {
  return $axios.get("/api/games/getMyGames");
}
/**
 * 获取游戏截图数据
 */
export const getPicByGameId = (id) => {
  return $axios.get("/api/gamesImg/allPic/" + id);
}
/**
 * 提交游戏截图数据
 */
export const submitGamePic = (data) => {
  $axios.post("/api/gamesImg/save", data, {'Content-Type': 'application/json'}).then(res => {
    let result = res.data;
    if (result.code === 200) {
      $message({
        type: 'success',
        message: '图像已经提交'
      })
    } else {
      $message({
        type: 'error',
        message: result.msg
      })
    }
  })
}


/**
 * 获取myAnime数据
 */
export const getAllAnime = () => {
  return $axios.get("/api/myAnime/allAnimes");
}
/**
 * 微博登录
 * @param code
 * @returns {Promise<AxiosResponse<any>>}
 */
export const weiboLogin = (code) => {
  return axios.create().get("/api/security/oauth2/weibo/save?code=" + code).then(res => {
    console.log("微博登录数据", res);
    let result = res.data;
    if (result.code === 200) {
      // 保存cookie,token
      $message({
        message: result.data.userName + '欢迎你',
        type: "success",
      });
      //保存token
      localStorage.setItem(TOKEN_NAME, result.data.token);
      //保存用户信息
      store.commit('CHANGE_USER', result.data);
      localStorage.setItem("USER", JSON.stringify(result.data));
      //路由跳转
      route.push({
        name: 'LayOut'
      });
    } else {
      $notify({
        type: 'error',
        message: result.msg,
        title: '授权失败'
      })
    }
  });
}
/**
 * 微博授权
 */
export const thirdAuth = (url) => {
  return axios.create().get(url);
}

/**
 * 获取第三方应用注册信息
 */
export const getAppMessage = (platform) => {
  return $axios.get("/api/security/oauth2/" + platform);
}

/**
 * 邮箱登录发送验证码
 */
export const sendMail = (mailAddr) => {
  refreshAxios();
  return $axios.get("/api/security/sendMail/" + mailAddr);
}

/**
 * 文件下载统计工具
 */
export const downLoadStatistic = (year, month) => {
  return $axios.get("/api/file/downloadStatistic/" + year + "/" + month)
}

/**
 * 获取文件上传统计数据
 */
export const getUploadStaticMessage = (year, month) => {
  return $axios.get("/api/file/static/" + year + "/" + month);
}
/**
 * 验证remember的cookie是否可用
 * @returns {boolean}
 */
export const validRemember = function () {
  let code = false;
  let remember = VueCookie.get(REMEMBER_COOKIE);
  console.log("rememberCookie :", remember)
  if (remember !== null && remember.length > 0) {
    axios.get("/api/file/allNames").then(res => {
      console.log("result", res.data);
      if (result.code !== 505) {
        console.log("code:", res.data.code)
        code = true;
      }
    });
  }
  return code;
}

/**
 * 登录
 * @param loginForm
 */
export const loginRequest = function (loginForm) {
  axios.create().post("/api/login", $qs.stringify(loginForm)).then((res) => {
    let result = res.data;
    if (result.code === 200) {
      $message({
        message: result.data.userName + '欢迎你',
        type: "success",
      });
      console.log("登录成功,当前用户信息:", result);
      //保存token
      localStorage.setItem(TOKEN_NAME, result.data.token);
      //保存用户信息
      store.commit('CHANGE_USER', result.data);
      localStorage.setItem("USER", JSON.stringify(result.data));
      //路由跳转
      route.push({
        name: 'index'
      });
      //刷新路由对象
      refreshAxios();
    } else {
      $notify({
        title: '登录验证异常',
        message: result.msg,
        type: 'error'
      })
    }
  }).catch((err) => {
    let errorRes = err.response.data;
    console.log(errorRes.msg)
    console.log(errorRes)
    $notify({
      title: errorRes.code,
      message: errorRes.msg,
      type: 'error'
    })
  });
}
/**
 * token续期
 */
export const renewalToken = function () {
  refreshAxios();
  $axios.get("/api/security/renewal").then((res) => {
    let result = res.data;
    switch (result.code) {
      case 200:
        break;
      case 101:
      case 103:
        $notify({
          title: 'token续期失败',
          type: 'warning',
          message: "续期:" + result.msg
        });
        break;
      default:
        $message({
          type: "error",
          message: 'token续期出现了,意料之外的麻烦'
        })
    }
  }).catch((err) => {
    $notify({
      type: "error",
      message: err,
      title: '发送/api/security/renewal失败了'
    })
  })
  refreshAxios();
}
// 检验token合法性
export const validateToken = function (to, from, next) {
  $axios.get("/api/security/validate").then(res => {
    let result = res.data;
    switch (result.code) {
      case 200:
        next();
        break;
      case 101:
      //TOKEN 过期了,或者token有误
      case 102:
        //TOKEN 不存在
        localStorage.clear();
        $message({
          type: 'error',
          message: result.msg
        });
        next("/login");
        break;
      default:
        $message("token出现了其他问题,反正不是200")
        localStorage.removeItem(TOKEN_NAME);
        route.push("/login");
    }
  })
  refreshAxios();
}


export const submitVideo = function (videoData) {
  return $axios.post("/api/video/save", videoData)
}

export const getShortVideo = function (url, config) {
  return $axios.get(url, config)
}

export const keywordSearchFile = function (keyWord, page) {
  return $axios.post("/api/file/keyWord/" + keyWord, page);
}
//评论相关-----------------------------------------------------------------------
export const saveComment = function (comment) {
  return $axios.post("/api/comments/save", comment);
}
export const getCommentByFileId = function (fileId) {
  return $axios.get("/api/comments/file/" + fileId);
}
export const getLatestComment = function (num) {
  return $axios.get("/api/comments/latest/" + num);
}
//上传记录-------------------------------------------------------------------------------------------
export const saveUploadLog = function (data) {
  return $axios.post("/api/uploadLog/save", data).then(res => {
    if (res.data.code === 200) {
      $message({
        type: 'success',
        message: "您的文件已经收到"
      })
    } else {
      $message({
        type: 'error',
        message: "出了点小问题,我们将会联系维修人员,请您稍安勿躁"
      })
    }
  });
}
//文件类型相关-----------------------------------------------------------------------------------------------------------
export const getFileTypeName = function (sourceName) {
  return $axios.get("/api/fileType/source2Name/" + sourceName);
}

// 文件相关--------------------------------------------------------------------------------------------------------------
export const getFileById = function (id) {
  return $axios.get("/api/file/" + id);
}


export const allFile = function (page, cat) {
  if (cat != null && cat.length < 1) {
    return $axios.post("/api/file/all/" + '', page);
  } else {
    return $axios.post("/api/file/all/" + cat, page);
  }
}

export const fileRoot = function () {
  return $axios.get("/api/fileType/root");
}

export const saveFile = function (ruleForm) {
  $axios.post("/api/file/save", ruleForm, {
    'Content-Type': 'application/json',
  }).then((res) => {
    if (res.data.code === 200) {
      $notify({
        title: '成功',
        message: '文件已提交',
        type: 'success'
      })
      this.ruleForm = {};
    } else {
      $notify({
        title: '异常',
        message: res.data.msg,
        type: 'warning'
      })
    }
  })
}



